local pbc		= require "protobuf.c"
local P
local skynet	= require "skynet"
require "skynet.manager"
local register_flag={}
local wait_list={}

function response.getenv()
	return P
end

local function register_file(protobuf,name,file)
	skynet.error("===============register proto",file)
	protobuf.register_file(file)
	register_flag[name]=true
end

local function get_import_list(file,name)
	local list={}
	local start
	for line in io.lines(file) do
		if line:find("proto") then
			for w in line:gmatch("([%w_]+).proto") do
				if w~=name then
					table.insert(list, w) 
				end
			end
			start=true
		elseif start then
			break
		end
	end
	return list
end

function init(path)
	P=assert(pbc._env_new())
	debug.getregistry().PROTOBUF_ENV=P
	local protobuf  = require"protobuf"
	if not os.execute("ls "..path.." >temppb.tmp") then
		skynet.error("os excute error")
		skynet.sleep(10)
		skynet.abort()
	end
	for line in io.lines("temppb.tmp") do
		local name=line:match("([%w_]+)[.]pb")
		local file=path..line
		local list=get_import_list(file,name)
		if next(list) then
			wait_list[name]={file=file,list=list}
		else
			register_file(protobuf,name,file)
		end
	end
	while next(wait_list) do
		local flag
		for name,v in pairs(wait_list) do
			local r=true
			for k2,v2 in ipairs(v.list) do
				if not register_flag[v2] then
					r=false
					break
				end
			end
			if  r then
				register_file(protobuf,name,v.file)
				register_flag[name]=true
				wait_list[name]=nil
				flag=true
			end
		end
		if not flag then
			skynet.error("register pb error")
			skynet.sleep(1)
			skynet.abort()
		end
	end
end

function exit(...)

end
